﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataLayer;
using System.Xml;

namespace BusinessLayer
{
    public class MovieCTR : IMovieCTR
    {
        private List<Movie> _movies;

        public MovieCTR() {
            _movies = new List<Movie>();
        }

        public void AddMovie(string title, string genre, string time, string description, double price)
        {
            Movie movie = new Movie(title, genre, time, description, price);
            _movies.Add(movie);
        }

        public List<Movie> getMovies()
        {
            return _movies;
        }    

        public void searchIMDBMovies(string search)
        {
            // Lad sådan at søge strengen bliver url-friendly
            loadMovies(search);
        }

        private void loadMovies(string search)
        {
            XmlDocument xmlMovies = new XmlDocument();
            xmlMovies.Load("http://imdbapi.org/?title="+search+"&type=xml&plot=simple&episode=1&limit=10&yg=0&mt=none&lang=en-US&offset=&aka=simple&release=simple&business=0&tech=0");

            //XmlNodeList nodeList = xmlMovies.SelectNodes("//*[name()='title']");
            XmlNodeList nodeList = xmlMovies.SelectNodes("/IMDBDocumentList/item");

            foreach (XmlNode node in nodeList)
            {
                createMovieFromXml(node);
            }
        }

        private void createMovieFromXml(XmlNode root)
        {
            // Doesn't need to be item[1] because SelectSingleNode only selects first item
            Movie movie = new Movie(root.SelectSingleNode("./title").InnerText, root.SelectSingleNode("./genres/item").InnerText,
                                    root.SelectSingleNode("./runtime/item").InnerText, "Beskrivelse", 90.0);
            _movies.Add(movie);
        }
    }
}
